<template>
  <view class="chat-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="navbar-content">
        <view class="navbar-left" @tap="goBack">
          <u-icon name="arrow-left" size="20" color="#333"></u-icon>
        </view>
        <view class="navbar-center">
          <view class="author-card-navbar" v-if="otherUser">
            <image v-if="otherUser.avatar" class="author-avatar-navbar" :src="otherUser.avatar" mode="aspectFill">
            </image>
            <image v-else class="author-avatar-navbar" src="/static/logo.png" mode="aspectFill"></image>
            <view class="author-info-navbar">
              <text class="author-name-navbar">
                {{ otherUser.nickname || otherUser.username || '匿名用户' }}
              </text>
            </view>
          </view>
        </view>
        <view class="navbar-right"></view>
      </view>
    </view>

    <!-- 消息列表 -->
    <scroll-view class="message-list" scroll-y :scroll-top="scrollTop" :scroll-into-view="scrollIntoView"
      @scrolltolower="loadMoreMessages">
      <view class="message-wrapper">
        <view v-for="(message, index) in messages" :key="message.id || index" :id="`msg-${message.id}`"
          class="message-item" :class="{ 'my-message': message.senderId === currentUserId }">
          <!-- 对方消息 -->
          <template v-if="message.senderId !== currentUserId">
            <image class="message-avatar" :src="otherUser?.avatar || '/static/logo.png'" mode="aspectFill"></image>
            <view class="message-content-wrapper">
              <template v-if="message.type === MessageType.TEXT">
                <view class="message-bubble other">
                  <text class="message-text">
                    {{ message.content }}
                  </text>
                </view>
              </template>
              <template v-else-if="message.type === MessageType.IMAGE">
                <image class="message-media-image" :src="message.mediaUrl" mode="aspectFill"
                  @tap="previewImage(message.mediaUrl || '')"></image>
              </template>
              <template v-else-if="message.type === MessageType.VIDEO">
                <video class="message-media-video" :src="message.mediaUrl" controls :show-center-play-btn="false"
                  :enable-progress-gesture="true"></video>
              </template>
              <view class="message-meta">
                <text class="message-time">{{ formatTime(message.createdAt) }}</text>
              </view>
            </view>
          </template>

          <!-- 我的消息（右侧，头像在最右，气泡在头像左侧） -->
          <template v-else>
            <view class="message-content-wrapper my">
              <template v-if="message.type === MessageType.TEXT">
                <view class="message-bubble my">
                  <text class="message-text my-text">
                    {{ message.content }}
                  </text>
                </view>
              </template>
              <template v-else-if="message.type === MessageType.IMAGE">
                <image class="message-media-image" :src="message.mediaUrl" mode="aspectFill"
                  @tap="previewImage(message.mediaUrl || '')"></image>
              </template>
              <template v-else-if="message.type === MessageType.VIDEO">
                <video class="message-media-video" :src="message.mediaUrl" controls :show-center-play-btn="false"
                  :enable-progress-gesture="true"></video>
              </template>
              <view class="message-meta my">
                <text class="message-time">{{ formatTime(message.createdAt) }}</text>
                <text v-if="message.isRead" class="read-status">已读</text>
                <text v-else class="read-status unread">未读</text>
              </view>
            </view>
            <image class="message-avatar" :src="currentUserAvatar || '/static/logo.png'" mode="aspectFill"></image>
          </template>
        </view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-area">
      <view class="input-box">
        <view class="input-left">
          <view class="icon-btn" @tap="showMoreOptions = !showMoreOptions">
            <u-icon name="plus" size="24" color="#666"></u-icon>
          </view>
        </view>
        <input class="message-input" v-model="inputContent" placeholder="输入消息..." :adjust-position="true"
          :hold-keyboard="true" @confirm="sendMessage" @input="onInput" />
        <view class="input-right">
          <view v-if="inputContent.trim()" class="send-btn" @tap="sendMessage">
            <text class="send-text">发送</text>
          </view>
          <view v-else class="icon-btn" @tap="showMoreOptions = !showMoreOptions">
            <u-icon name="account" size="24" color="#666"></u-icon>
          </view>
        </view>
      </view>

      <!-- 更多选项 -->
      <view v-if="showMoreOptions" class="more-options">
        <view class="option-item" @tap="chooseImage">
          <u-icon name="image" size="32" color="#4A90E2"></u-icon>
          <text class="option-text">照片</text>
        </view>
        <view class="option-item" @tap="chooseVideo">
          <u-icon name="play-circle" size="32" color="#4A90E2"></u-icon>
          <text class="option-text">视频</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, nextTick } from 'vue'
import { onShow, onHide } from '@dcloudio/uni-app'
import {
  getConversationMessages,
  sendMessage as sendMessageApi,
  markConversationAsRead,
  type MessageInfo,
  MessageType
} from '@/api/messages'
import { uploadFile } from '@/api/works'
import { useUser } from '@/composables/useUser'

// 状态栏高度
const statusBarHeight = ref(0)

// 路由参数
const props = defineProps<{
  conversationId?: string
  userId?: string  // 对方用户ID
}>()

// 当前用户信息
const { userInfo, initUser } = useUser()
// 初始化用户信息
initUser()
const currentUserId = computed(() => userInfo.value?.id || 0)
const currentUserAvatar = computed(() => userInfo.value?.avatar)

// 对方用户信息
const otherUser = ref<{ id: number; username?: string; nickname?: string; avatar?: string } | null>(null)

// 消息列表
const messages = ref<MessageInfo[]>([])

// 输入内容
const inputContent = ref('')

// 显示更多选项
const showMoreOptions = ref(false)

// 滚动相关
const scrollTop = ref(0)
const scrollIntoView = ref('')

// 分页
const page = ref(1)
const limit = ref(50)
const hasMore = ref(true)
const loading = ref(false)

// 会话ID
const conversationId = ref('')

// 定时器（用于轮询新消息）
let pollTimer: ReturnType<typeof setInterval> | null = null

// 消息排序（按创建时间正序）
const sortMessagesAsc = (list: MessageInfo[]): MessageInfo[] => {
  return [...list].sort(
    (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
  )
}

// 合并并去重消息
const mergeMessages = (existing: MessageInfo[], incoming: MessageInfo[]): MessageInfo[] => {
  const map = new Map<string | number, MessageInfo>()
  const addMessage = (msg: MessageInfo) => {
    const key = msg.id ?? `${msg.senderId}_${msg.createdAt}`
    map.set(key, msg)
  }

  existing.forEach(addMessage)
  incoming.forEach(addMessage)

  return sortMessagesAsc(Array.from(map.values()))
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 格式化时间
const formatTime = (timeStr: string): string => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)

  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`

  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  return `${month}/${day} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
}

// 生成会话ID
const generateConversationId = (userId1: number, userId2: number): string => {
  return userId1 < userId2 ? `${userId1}_${userId2}` : `${userId2}_${userId1}`
}

// 加载消息
const loadMessages = async (isLoadMore: boolean = false) => {
  if (loading.value || (!hasMore.value && isLoadMore)) return

  loading.value = true
  try {
    const currentPage = isLoadMore ? page.value + 1 : 1
    const response = await getConversationMessages(conversationId.value, currentPage, limit.value)

    if (response.data && response.data.length > 0) {
      const incoming = sortMessagesAsc(response.data)
      if (isLoadMore) {
        messages.value = mergeMessages(messages.value, incoming)
        page.value = currentPage
      } else {
        messages.value = incoming
        page.value = 1
        nextTick(() => {
          scrollToBottom()
        })
      }

      hasMore.value = response.data.length >= limit.value

      // 获取对方用户信息
      if (response.data.length > 0 && !otherUser.value) {
        for (const msg of response.data) {
          if (msg.senderId !== currentUserId.value && msg.sender) {
            otherUser.value = msg.sender
            break
          } else if (msg.receiverId !== currentUserId.value && msg.receiver) {
            otherUser.value = msg.receiver
            break
          }
        }

        // 如果还是没有，设置默认值
        if (!otherUser.value && response.data.length > 0) {
          const firstMessage = response.data[0]
          const otherUserId = firstMessage.senderId === currentUserId.value
            ? firstMessage.receiverId
            : firstMessage.senderId
          otherUser.value = {
            id: otherUserId,
            username: '用户',
            avatar: '/static/logo.png'
          }
        }
      }
    } else {
      hasMore.value = false
    }

    // 标记会话为已读
    if (!isLoadMore) {
      await markConversationAsRead(conversationId.value)
    }
  } catch (error: any) {
    console.error('加载消息失败:', error)
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 加载更多消息
const loadMoreMessages = () => {
  if (hasMore.value && !loading.value) {
    loadMessages(true)
  }
}

// 发送消息
const sendMessageHandler = async () => {
  const content = inputContent.value.trim()
  if (!content || !otherUser.value) return

  const receiverId = otherUser.value.id

  // 乐观更新：立即显示消息
  const tempMessage: MessageInfo = {
    id: Date.now(), // 临时ID
    conversationId: conversationId.value,
    senderId: currentUserId.value,
    receiverId: receiverId,
    type: MessageType.TEXT,
    content: content,
    isRead: false,
    createdAt: new Date().toISOString(),
    sender: {
      id: currentUserId.value,
      username: userInfo.value?.username,
      avatar: currentUserAvatar.value || undefined
    }
  }

  messages.value.push(tempMessage)
  inputContent.value = ''
  showMoreOptions.value = false

  // 滚动到底部
  nextTick(() => {
    scrollToBottom()
  })

  try {
    // 发送到服务器
    const sentMessage = await sendMessageApi({
      receiverId: receiverId,
      type: MessageType.TEXT,
      content: content
    })

    // 替换临时消息
    const index = messages.value.findIndex(m => m.id === tempMessage.id)
    if (index !== -1) {
      messages.value[index] = sentMessage
    }
  } catch (error: any) {
    console.error('发送消息失败:', error)
    uni.showToast({
      title: error.message || '发送失败',
      icon: 'none'
    })

    // 移除失败的消息
    const index = messages.value.findIndex(m => m.id === tempMessage.id)
    if (index !== -1) {
      messages.value.splice(index, 1)
    }
  }
}

// 发送消息（别名）
const sendMessage = sendMessageHandler

// 输入事件
const onInput = () => {
  // 可以在这里实现"正在输入"功能
}

// 滚动到底部
const scrollToBottom = () => {
  if (messages.value.length > 0) {
    const lastMessage = messages.value[messages.value.length - 1]
    scrollIntoView.value = `msg-${lastMessage.id}`
    nextTick(() => {
      scrollIntoView.value = ''
    })
  }
}

// 文件大小限制（单位：字节）
const IMAGE_MAX_SIZE = 5 * 1024 * 1024      // 5MB
const VIDEO_MAX_SIZE = 50 * 1024 * 1024     // 50MB

// 选择图片并发送
const chooseImage = async () => {
  showMoreOptions.value = false
  try {
    const res = await uni.chooseImage({
      count: 1,
      sourceType: ['album', 'camera']
    })

    const tempFilePath = res.tempFilePaths?.[0]
    const tempFile = (res as any).tempFiles?.[0]

    if (!tempFilePath || !tempFile) return

    // 大小限制
    if (tempFile.size > IMAGE_MAX_SIZE) {
      uni.showToast({
        title: '图片大小不能超过5MB',
        icon: 'none'
      })
      return
    }

    if (!otherUser.value) return

    const receiverId = otherUser.value.id

    // 本地临时显示的消息（发送中）
    const tempMessage: MessageInfo = {
      id: Date.now(),
      conversationId: conversationId.value,
      senderId: currentUserId.value,
      receiverId,
      type: MessageType.IMAGE,
      content: '',
      mediaUrl: tempFilePath,
      isRead: false,
      createdAt: new Date().toISOString(),
      sender: {
        id: currentUserId.value,
        username: userInfo.value?.username,
        avatar: currentUserAvatar.value || undefined
      }
    }

    messages.value.push(tempMessage)
    nextTick(scrollToBottom)

    try {
      // 上传图片
      uni.showLoading({ title: '发送中...', mask: true })
      const url = await uploadFile(tempFilePath, 'image')

      // 调用发送消息接口
      const sent = await sendMessageApi({
        receiverId,
        type: MessageType.IMAGE,
        content: '',
        mediaUrl: url
      })

      const index = messages.value.findIndex(m => m.id === tempMessage.id)
      if (index !== -1) {
        messages.value[index] = sent
      }
    } catch (error: any) {
      console.error('发送图片失败:', error)
      uni.showToast({
        title: error.message || '发送图片失败',
        icon: 'none'
      })
      const index = messages.value.findIndex(m => m.id === tempMessage.id)
      if (index !== -1) {
        messages.value.splice(index, 1)
      }
    } finally {
      uni.hideLoading()
    }
  } catch (error) {
    console.error('选择图片失败:', error)
  }
}

// 选择视频并发送
const chooseVideo = async () => {
  showMoreOptions.value = false
  try {
    const res = await uni.chooseVideo({
      sourceType: ['album', 'camera']
    })

    const tempFilePath = res.tempFilePath
    const size = (res as any).size as number | undefined

    if (!tempFilePath || !size) return

    // 大小限制
    if (size > VIDEO_MAX_SIZE) {
      uni.showToast({
        title: '视频大小不能超过50MB',
        icon: 'none'
      })
      return
    }

    if (!otherUser.value) return

    const receiverId = otherUser.value.id

    const tempMessage: MessageInfo = {
      id: Date.now(),
      conversationId: conversationId.value,
      senderId: currentUserId.value,
      receiverId,
      type: MessageType.VIDEO,
      content: '',
      mediaUrl: tempFilePath,
      isRead: false,
      createdAt: new Date().toISOString(),
      sender: {
        id: currentUserId.value,
        username: userInfo.value?.username,
        avatar: currentUserAvatar.value || undefined
      }
    }

    messages.value.push(tempMessage)
    nextTick(scrollToBottom)

    try {
      uni.showLoading({ title: '发送中...', mask: true })
      const url = await uploadFile(tempFilePath, 'video')

      const sent = await sendMessageApi({
        receiverId,
        type: MessageType.VIDEO,
        content: '',
        mediaUrl: url
      })

      const index = messages.value.findIndex(m => m.id === tempMessage.id)
      if (index !== -1) {
        messages.value[index] = sent
      }
    } catch (error: any) {
      console.error('发送视频失败:', error)
      uni.showToast({
        title: error.message || '发送视频失败',
        icon: 'none'
      })
      const index = messages.value.findIndex(m => m.id === tempMessage.id)
      if (index !== -1) {
        messages.value.splice(index, 1)
      }
    } finally {
      uni.hideLoading()
    }
  } catch (error) {
    console.error('选择视频失败:', error)
  }
}

// 预览图片
const previewImage = (url: string) => {
  if (!url) return
  uni.previewImage({
    urls: [url],
    current: url
  })
}

// 轮询新消息
const startPolling = () => {
  if (pollTimer) return

  pollTimer = setInterval(async () => {
    if (loading.value) return

    try {
      const response = await getConversationMessages(conversationId.value, 1, 1)
      if (response.data && response.data.length > 0) {
        const latestMessage = response.data[response.data.length - 1]
        const exists = messages.value.some(m => m.id === latestMessage.id)

        if (!exists && latestMessage.senderId !== currentUserId.value) {
          // 有新消息，重新加载
          await loadMessages(false)
        }
      }
    } catch (error) {
      console.error('轮询消息失败:', error)
    }
  }, 3000) // 每3秒轮询一次
}

// 停止轮询
const stopPolling = () => {
  if (pollTimer) {
    clearInterval(pollTimer)
    pollTimer = null
  }
}

// 页面显示
onShow(() => {
  startPolling()
})

// 页面隐藏
onHide(() => {
  stopPolling()
})

// 页面加载
onMounted(async () => {
  // 设置状态栏高度
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight || 20

  // 获取路由参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1] as any
  const options = currentPage.options || {}

  const userId = options.userId
  const convId = options.conversationId

  if (convId) {
    conversationId.value = convId
  } else if (userId) {
    const otherUserId = parseInt(userId)
    conversationId.value = generateConversationId(currentUserId.value, otherUserId)
    // 设置对方用户信息（临时，实际应该从API获取）
    otherUser.value = {
      id: otherUserId,
      username: '用户',
      avatar: '/static/logo.png'
    }
  } else {
    uni.showToast({
      title: '参数错误',
      icon: 'none'
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
    return
  }

  // 加载消息（会设置对方用户信息）
  await loadMessages()

  // 设置导航栏标题
  if (otherUser.value) {
    uni.setNavigationBarTitle({
      title: otherUser.value.username || otherUser.value.nickname || '聊天'
    })
  }

  // 开始轮询
  startPolling()
})

// 页面卸载
onUnmounted(() => {
  stopPolling()
})
</script>

<style scoped>
.chat-container {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

/* 自定义导航栏 */
.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
}

.navbar-content {
  height: 88rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 0 24rpx;
}

.navbar-left,
.navbar-right {
  width: 88rpx;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.navbar-right {
  justify-content: flex-end;
}

.navbar-center {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.author-card-navbar {
  flex-direction: row;
  display: flex;
  align-items: center;
}

.author-avatar-navbar {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  margin-right: 16rpx;
}

.author-info-navbar {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.author-name-navbar {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
}

/* 消息列表 */
.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx;
  /* 预留给自定义导航栏的空间，避免被遮挡 */
  margin-top: 180rpx;
}

.message-wrapper {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
  /* 预留底部输入区域的空间，避免最后一条消息被遮挡 */
  padding-bottom: 160rpx;
}

.message-item {
  display: flex;
  align-items: flex-start;
  gap: 15rpx;
}

.message-item.my-message {
  justify-content: flex-end;
  /* 自己消息整体靠右 */
}

.message-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  flex-shrink: 0;
}

.message-content-wrapper {
  max-width: 60%;
  display: flex;
  flex-direction: column;
}

.message-content-wrapper.my {
  align-items: flex-end;
}

.message-bubble {
  padding: 20rpx 24rpx;
  border-radius: 12rpx;
  position: relative;
  word-wrap: break-word;
}

.message-bubble.other {
  background-color: #fff;
  border-top-left-radius: 4rpx;
}

.message-bubble.my {
  background-color: #4e8cee;
  /* 自己消息：蓝色气泡 */
  border-top-right-radius: 4rpx;
}

.message-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
}

.message-bubble.my .message-text,
.message-text.my-text {
  color: #fff;
  /* 自己消息文字白色 */
}

.message-media-image {
  max-width: 400rpx;
  max-height: 400rpx;
  border-radius: 8rpx;
  margin-top: 6rpx;
}

.message-media-video {
  width: 420rpx;
  max-height: 480rpx;
  border-radius: 12rpx;
  background-color: #000;
  margin-top: 6rpx;
}

.message-meta {
  margin-top: 8rpx;
  display: flex;
  align-items: center;
  gap: 12rpx;
  font-size: 20rpx;
  color: #999;
}

.message-meta.my {
  justify-content: flex-end;
}

.message-time {
  font-size: 20rpx;
  color: #999;
}

.message-status {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-top: 8rpx;
}

.read-status {
  font-size: 20rpx;
  color: #999;
}

.read-status.unread {
  color: #ff9500;
}

/* 输入区域 */
.input-area {
  background-color: #fff;
  border-top: 1rpx solid #e5e5e5;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
}

.input-box {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.input-left,
.input-right {
  display: flex;
  align-items: center;
}

.message-input {
  flex: 1;
  background-color: #f5f5f5;
  border-radius: 40rpx;
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: #333;
  min-height: 60rpx;
  max-height: 200rpx;
}

.icon-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-btn {
  padding: 12rpx 30rpx;
  background-color: #4A90E2;
  border-radius: 40rpx;
}

.send-text {
  font-size: 28rpx;
  color: #fff;
}

/* 更多选项 */
.more-options {
  display: flex;
  gap: 40rpx;
  padding: 30rpx;
  border-top: 1rpx solid #e5e5e5;
}

.option-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10rpx;
}

.option-text {
  font-size: 24rpx;
  color: #666;
}
</style>